package com.baizhi.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.LineCaptcha;
import com.baizhi.annotation.LogAnnotation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("admin")
public class CmfzAdminController {

    @RequestMapping("adminLogin")
    @ResponseBody
    @LogAnnotation(content="登录",type="login")
    public String adminLogin(String username,String password,String code){
        Session session = SecurityUtils.getSubject().getSession();
        ICaptcha captcha = (ICaptcha) session.getAttribute("captcha");

        String status = "";
//        1.将页面输入的账号密码封装到令牌中
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//        2.获取主体 调用主体的login方法
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            System.out.println("成功");
            status = "成功";

//            验证代码式授权
            if (subject.hasRole("admin")) {
                System.out.println("张三是普通管理员");
            }

            if (subject.isPermitted("banner:delete")) {
                System.out.println("张三可以删除轮播图");
            }else {

            }

        }catch (Exception e){
            System.out.println("错误");
            status = "错误";
        }

        return status;
    }

    @RequestMapping("getCaptcha")
    public void getCaptcha(HttpServletResponse response) throws IOException {
        Session session = SecurityUtils.getSubject().getSession();
        //定义图形验证码的长和宽
        ICaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
//        获取验证码内容
        System.out.println(captcha.getCode());
//        将验证码对象放到session中
        session.setAttribute("captcha",captcha);
//        通过流写出
        captcha.write(response.getOutputStream());
    }

    /**
     * 校验角色
     *  @RequiresRoles(value = "admin") 拥有角色admin 才能访问这个方法
     * @return
     */
    @RequiresRoles(value = "admin")
    @RequestMapping("testRole")
    @ResponseBody
    public String testRole(){
        return "testRole";
    }

    /**
     * 校验权限
     * @RequiresPermissions(value = "banner:select") 拥有权限banner:select 才能访问这个方法 没有抛异常
     * @return
     */
    @RequiresPermissions(value = "banner:select")
    @RequestMapping("testPermission")
    @ResponseBody
    public String testPermission(){
        return "testPermission";
    }
}
